package com.mqtt.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis配置类
 */
@Slf4j
@Configuration
public class RedisConfiguration {
    
    @Value("${redis.host:localhost}")
    private String host;
    
    @Value("${redis.port:6379}")
    private int port;
    
    @Value("${redis.password:}")
    private String password;
    
    @Value("${redis.database:0}")
    private int database;
    
    @Value("${redis.timeout:3000}")
    private int timeout;
    
    @Value("${redis.pool.max.active:8}")
    private int maxActive;
    
    @Value("${redis.pool.max.idle:8}")
    private int maxIdle;
    
    @Value("${redis.pool.min.idle:0}")
    private int minIdle;
    
    @Value("${redis.pool.max.wait:3000}")
    private long maxWait;
    
    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWait);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        config.setMinEvictableIdleTimeMillis(60000);
        config.setTimeBetweenEvictionRunsMillis(30000);
        config.setNumTestsPerEvictionRun(-1);
        
        JedisPool pool;
        if (password != null && !password.isEmpty()) {
            pool = new JedisPool(config, host, port, timeout, password, database);
        } else {
            pool = new JedisPool(config, host, port, timeout, null, database);
        }
        
        log.info("Redis pool initialized: {}:{}/{}", host, port, database);
        return pool;
    }
}